package dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import bean.User;

public class UserDAO extends DAO<User> {

	public UserDAO(SessionFactory factory) {
		super(factory);
	}

	public User lookUpByUsername(String name) {
		List<User> list = this.getByAttribute("username", name, User.class);
		if (list != null && list.size() > 0) {
			User user = list.get(0);
			if(user.getUsername().equals(name))
				return user;
		}
		return null;
	}
	
	public ArrayList<String> create(User user)
	{
		ArrayList<String> errors = new ArrayList<String>();
		Transaction tx = null;
		Session session = null;
		try {				
			session = this.getSession();
			tx = session.beginTransaction();
			session.save(user);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			errors.add(e.getMessage());
			return errors;
		} finally {
			if(session != null)	session.close();
		}
		return errors;
	}
}
